//
//  AppTask.m
//  helper
//
//  Created by huangyi on 12-11-20.
//  Copyright (c) 2012年 huangyi. All rights reserved.
//

#import "TaskQueue.h"
#import "NSString+utils.h"
#import "NSArray+utils.h"
#import "NSMutableArray+utils.h"

@interface TaskQueue ()

@property(nonatomic,strong)NSMutableArray *queue;
@property(nonatomic)dispatch_queue_t dispatch;

@end

@implementation TaskQueue


+(TaskQueue*)shared{
    static TaskQueue *singleton=nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        singleton=[[TaskQueue alloc] init];
    });
    return singleton;
}
-(id)init{
    self=[super init];
    if (self) {
        self.queue=[NSMutableArray array];
        NSString *label=[NSString stringWithFormat:@"task-queue-%@",uniqueID()];
        self.dispatch=dispatch_queue_create(label.UTF8String, 0);
        self.running=NO;
    }
    return self;
}
-(NSUInteger)numOfTasks{
    return self.queue.count;
}

-(void)run_next_task{
    dispatch_async(self.dispatch, ^{
        @autoreleasepool {
            dispatch_block_t code=self.queue.firstObject;
            [self.queue removeFirstObject];
            if (code) {
                code();
            }
        }
        if (self.numOfTasks==0) {
            self.running=NO;
        }
        if (self.running) {
            [self run_next_task];
        }
    });
}
-(void)run{
    if (!self.running) {
        self.running=YES;
        [self run_next_task];
    }
}
-(void)pause{
    if (self.running) {
        self.running=NO;
    }
}
-(void)cancelAll{
    [self pause];
    [self.queue removeAllObjects];
}

-(NSString*)addTask:(dispatch_block_t)code{
    NSString *taskid=nil;
    if (code) {
        taskid=uniqueID();
        [self.queue addObject:code];
    }
    return taskid;
}
-(NSString*)insertTask:(dispatch_block_t)code{
    NSString *taskid=nil;
    if (code) {
        taskid=uniqueID();
        [self.queue insertObject:code atIndex:0];
    }
    return taskid;
}

@end
